package com.easysoft.commons.handler;

import com.easysoft.commons.entity.Message;
import com.easysoft.commons.utils.JSONUtils;
import com.easysoft.commons.utils.UUIDUtils;
import com.easysoft.commons.utils.WebConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.*;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CustomerServiceHandler implements WebSocketHandler {
    private static final Logger logger;
    private static final ConcurrentHashMap<String, WebSocketSession> members;

    static {
        members = new ConcurrentHashMap<>();
        logger = LoggerFactory.getLogger(CustomerServiceHandler.class);
    }


    /**
     * 连接完成时触发
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        Map attributes = webSocketSession.getAttributes();
        String uid = attributes.get(WebConstants.SESSION_USER_ID).toString();
        Message message = new Message();
        message.setType(1);
        message.setSendFrom(UUIDUtils.emptyUUID());
        message.setContent(uid);
        message.setDate(new Date());
        sendMessageToAll(JSONUtils.object2Json(message));
        members.put(uid, webSocketSession);
    }

    /**
     * 消息处理
     */
    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        Message message = JSONUtils.json2Object((String) webSocketMessage.getPayload(), Message.class);
        String userId = (String) webSocketSession.getAttributes().get(WebConstants.SESSION_USER_ID);
        if (message != null) {
            if (message.getType() == 9) {
                Message newMessage = new Message();
                newMessage.setDate(new Date());
                newMessage.setSendFrom(UUIDUtils.emptyUUID());
                newMessage.setType(9);
                newMessage.setContent(members.keys());
                webSocketSession.sendMessage(new TextMessage(JSONUtils.object2Json(newMessage)));
            }
            if (message.getType() == 2) {
                message.setDate(new Date());
                message.setSendFrom(userId);
                if (message.getSendTo().equals(UUIDUtils.emptyUUID())) {
                    sendMessageToAll(JSONUtils.object2Json(message));
                } else {
                    message.setType(3);
                    sendMessage(message);
                }
            }
        }
        //boolean flag = (Boolean) webSocketSession.getAttributes().get(WebConstants.IS_LOGIN);
        //SysChats chats = new SysChats();
        //chats.setUserId(flag ? userId : UUIDUtils.emptyUUID());
        //chats.setAcceptId(message.sendTo);
        //chats.setChatContent(message.content);
        //chats.setIp((String) webSocketSession.getAttributes().get("ip"));
        //chats.setIsStatus(0);
        //sendMessage(message);
    }

    /**
     * 会话异常触发
     */
    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        String uid = webSocketSession.getAttributes().get(WebConstants.SESSION_USER_ID).toString();
        Message message = new Message();
        message.setType(0);
        message.setSendFrom(UUIDUtils.emptyUUID());
        message.setContent(uid);
        message.setDate(new Date());
        sendMessageToAll(JSONUtils.object2Json(message));
        members.remove(uid);
        if (webSocketSession.isOpen()) {
            webSocketSession.close();
        }
    }

    /**
     * 断开连接
     */
    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        String uid = webSocketSession.getAttributes().get(WebConstants.SESSION_USER_ID).toString();
        Message message = new Message();
        message.setType(0);
        message.setSendFrom(UUIDUtils.emptyUUID());
        message.setContent(uid);
        message.setDate(new Date());
        sendMessageToAll(JSONUtils.object2Json(message));
        members.remove(uid);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public void sendMessageToAll(String message) throws Exception {
        if (members != null && members.size() > 0) {
            for (Object object : members.entrySet()) {
                Map.Entry entry = (Map.Entry) object;
                WebSocketSession socket = (WebSocketSession) entry.getValue();
                if (socket != null) {
                    if (socket.isOpen()) {
                        socket.sendMessage(new TextMessage(message));
                    } else {
                        members.remove(entry.getKey().toString());
                    }
                }
            }
        }
    }

    public void sendMessage(Message message) throws Exception {
        if (members != null && members.size() > 0) {
            WebSocketSession socket = members.get(message.getSendTo());
            if (socket != null) {
                if (socket.isOpen()) {
                    socket.sendMessage(new TextMessage(JSONUtils.object2Json(message)));
                } else {
                    members.remove(message.getSendTo());
                }
            }
        }
    }
}
